using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using HtmlAgilityPack;

namespace WebParseBuilder
{
    public partial class Form1 : Form
    {
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        public Form1()
        {
            InitializeComponent();
            tbInput.Text = Properties.Settings.Default.LastContent;
            tstbQuery.Text = Properties.Settings.Default.LastQuery;
            if (!string.IsNullOrEmpty(tbInput.Text))
                tsbParse_Click(this, new EventArgs());
        }

        private void tsbParse_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.LastContent = tbInput.Text;
            Properties.Settings.Default.Save();
            HtmlNode.ElementsFlags.Remove("form");
            HtmlNode.ElementsFlags.Remove("option");
            //HtmlNode.ElementsFlags.Remove("input");
            //HtmlNode.ElementsFlags["input"] = HtmlElementFlag.Closed | HtmlElementFlag.CanOverlap | HtmlElementFlag.Empty;
            doc.LoadHtml(tbInput.Text);
            doc.OptionOutputAsXml = true;
            //HtmlNode main = d.DocumentNode.SelectSingleNode(@"/html/body/div/div/div[@id=""page""]/div[@id=""main""]/div[@id=""col3""]/div[@id=""col3_content""]/div[@id=""main_content""]");
            doc.Save("tmp.xml");
            string dir = Directory.GetCurrentDirectory().Replace('\\','/');
            webBrowser.Navigate("file://" + dir + '/' + "tmp.xml");
        }

        private void tstbQuery_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && doc != null)
            {
                Properties.Settings.Default.LastQuery = tstbQuery.Text;
                Properties.Settings.Default.Save();
                HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes(tstbQuery.Text);
                if (nodes != null)
                    foreach (HtmlNode node in nodes)
                    {
                        MessageBox.Show(node.WriteTo());
                    }
                else
                    MessageBox.Show("No match!");
            }
        }
    }
}